﻿Imports System.Runtime.InteropServices

Module Module1
    Public FSO As Scripting.FileSystemObject = Nothing
    Public ObjSEApp As SolidEdgeFramework.Application = Nothing
    Public ObjSEAppType As Type
    Public ObjSEFilePropAPPType As Type
    Public intMaxNumberThenRestart As Integer = 0
    Public intSEECCount As Integer = 0
    Public StrFileNames As System.Collections.ArrayList
    Public intCtr As Integer = 0
    Public FSOLog As Scripting.FileSystemObject = Nothing
    Public txtStreamReportStatus As Scripting.TextStream = Nothing
    Public strSEInstalledPath As String = ""
    Public strSEVersion As String = ""
    Public SwitchExists As String = ""
    Public OpenSaveForm As Form
    Public blnRunFromCommandLine As Boolean = False
    Public blnCreatePDFsFromDrafts As Boolean = False
    Public strInputFilename As String = ""
    Public strLogFilename As String = ""
    Public strCommandLineCreatePDFs As String = ""
    Public strCommandLineInputFilename As String = ""
    Public strCommandLineInputUpdateDrawingViews As String = ""
    Public strCommandLineInputFitAndShade As String = ""
    Public strCommandLineInputRecompute As String = ""
    Public strCommandLineInputResetStatus As String = ""
    Public strCommandLineInputCheckAssembliesForCorruptLinks As String = ""
    Public DummySpreadsheetList As System.Collections.ArrayList
    Public blnRecompute As Boolean = False
    Public blnFitAndShade As Boolean = False
    Public strMacroPath As String = ""
    Public strMacroName As String = "DeleteInvalidSites.exe"
    Public strPathCMDLineOption As String = ""
    Public blnReadFilesFromFile As Boolean = False
    Public blnReadFilesFromFolder As Boolean = False
    Public blnUpdateDrawingViews As Boolean = False
    Public blnCheckAssemblyForCorruptLinks As Boolean = False
    Public blnResetStatus As Boolean = False
    Public blnTurnOffDisplayNextOccProp As Boolean = False
    Public blnCopyStyles As Boolean = False
    Public blnUpdateLinks As Boolean = False
    Public blnExtractPreviewBMP As Boolean = False


    Sub Garbage_Collect(ByVal obj As Object)
        Try
            '******* Added because of .NET
            If Not (obj Is Nothing) Then
                'Marshal.ReleaseComObject(obj)
                Marshal.FinalReleaseComObject(obj)
            End If
           
            '******* Added because of .NET
        Catch ex As Exception
            obj = Nothing
        End Try

    End Sub
    Public Sub Main(ByVal args As String())

        ObjSEAppType = Type.GetTypeFromProgID("SolidEdge.Application")

        ObjSEFilePropAPPType = Type.GetTypeFromProgID("SolidEdge.FileProperties")
        '"C:\_Work\VB\VB Programs\OpenSaveFromTextfile\Batch open.txt"



        

        If args.Length = 0 Then   ' then NOT running from commandline
            blnRunFromCommandLine = False
            StrFileNames = New ArrayList
            'must not be command line driven so show the form
            If OpenSaveForm Is Nothing Then
                OpenSaveForm = New Form1
                OpenSaveForm.ShowDialog()
                OpenSaveForm.TopMost = True
            Else
                OpenSaveForm.ShowDialog()
                OpenSaveForm.TopMost = True
            End If
            Exit Sub
        End If

        blnRunFromCommandLine = True

        blnReadFilesFromFile = True 'if run via commandline must use this option
        blnReadFilesFromFolder = False  'if run via commandline must use this option


        Try
            For Each arg As String In args
                ParseCommandlineInput(arg.ToString)
            Next arg
            strInputFilename = strCommandLineInputFilename
            strLogFilename = GetFilePath(strInputFilename) + "\OpenSaveLog.txt"


            '***** below gathers the input arguments for the supported options

            If strCommandLineCreatePDFs.ToUpper = "TRUE" Then
                blnCreatePDFsFromDrafts = True
            End If
            If strCommandLineCreatePDFs.ToUpper = "FALSE" Then
                blnCreatePDFsFromDrafts = False
            End If



            If strCommandLineInputUpdateDrawingViews.ToUpper = "TRUE" Then
                blnUpdateDrawingViews = True
            End If
            If strCommandLineInputUpdateDrawingViews.ToUpper = "FALSE" Then
                blnUpdateDrawingViews = False
            End If


            If strCommandLineInputFitAndShade.ToUpper = "TRUE" Then
                blnFitAndShade = True
            End If

            If strCommandLineInputFitAndShade.ToUpper = "FALSE" Then
                blnFitAndShade = False
            End If



            If strCommandLineInputRecompute.ToUpper = "TRUE" Then
                blnRecompute = True
            End If
            If strCommandLineInputRecompute.ToUpper = "FALSE" Then
                blnRecompute = False
            End If


            If strCommandLineInputCheckAssembliesForCorruptLinks.ToUpper = "TRUE" Then
                blnCheckAssemblyForCorruptLinks = True
            End If
            If strCommandLineInputCheckAssembliesForCorruptLinks.ToUpper = "FALSE" Then
                blnCheckAssemblyForCorruptLinks = False
            End If


            If strCommandLineInputResetStatus.ToUpper = "TRUE" Then
                blnResetStatus = True
            End If
            If strCommandLineInputResetStatus.ToUpper = "FALSE" Then
                blnResetStatus = False
            End If



        Catch ex As Exception

        End Try


        Call Process()



    End Sub



    Public Sub Process()

        Dim ii As Long = 0
        Dim pp As Integer
        Dim objDoc As Object = Nothing
        Dim obj3dWindow As SolidEdgeFramework.Window = Nothing
        Dim obj2dWindow As SolidEdgeDraft.SheetWindow = Nothing

        Dim strtempFilename As String = ""
        'Dim objView As SolidEdgeFramework.View = Nothing
        Dim vString As String


       

        Dim objModels As SolidEdgePart.Models = Nothing
        Dim objModel As SolidEdgePart.Model = Nothing
        Dim objFlatPatternModels As SolidEdgePart.FlatPatternModels = Nothing
        Dim objFlatPatternModel As SolidEdgePart.FlatPatternModel = Nothing


        Dim blnCorruptLinkFileProcessed As Boolean = False

        '******* Added because of .NET
        Try
            OleMessageFilter.Register()
        Catch ex As Exception
            'PrintLine("Error registering message filter.")
        End Try
        '******* Added because of .NET


        GetSolidEdgePath()



        If createLogFile() = False Then
            'MessageBox.Show("Error creating the log file " + Form1.TxtLogFileName.Text, "SE Utilities", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End If

        intMaxNumberThenRestart = 50

        If blnReadFilesFromFile = True Then
            If UCase(strInputFilename).EndsWith("TXT") Then
                ReadTextFile()
            End If

            If UCase(strInputFilename).EndsWith("CSV") Then
                DummySpreadsheetList = New ArrayList
                '   add function to red filenames plus path from the xml ordered list ReadTextFile()
                ReadFilenamesFromCSVFile(strInputFilename)
            End If
        End If


        'already got a list of files from recursing the folder specified in the dialog....  since running the UI (not via commandline input)

        'make sure Solid Edge is not running since we will be setting registry stuff
        Try
            ObjSEApp = Marshal.GetActiveObject("SolidEdge.Application")
            Do While ObjSEApp.Documents.Count <> 0
                ObjSEApp.DisplayAlerts = False
                ObjSEApp.ActiveDocument.close()
            Loop
            ObjSEApp.Quit()
            Garbage_Collect(ObjSEApp)
        Catch ex As Exception

        End Try
        

        '****************set the necessary registry stuff*************************************

        ' Set the assembly mode to open assemblies with Occurrences inactive
        SetAssemblyMode(1)

        ' Set the assembly mode to open assemblies with all Occurrences active.
        'SetAssemblyMode(2)

        'check to see if registry location exists
        SwitchExists = QueryValue(HKEY_CURRENT_USER, "Software\Unigraphics Solutions\Solid Edge\Version " & strSEVersion & "\Debug", "DocMgmt_OverrideStatusCheckForFileAccess")

        If SwitchExists = "" Then
            '-- Create key in CURRENT USER and set it
            SetKeyValue(HKEY_CURRENT_USER, "Software\Unigraphics Solutions\Solid Edge\Version " & strSEVersion & "\Debug", "DocMgmt_OverrideStatusCheckForFileAccess", "1", REG_DWORD)
        End If

        If SwitchExists = "0" Then
            '-- Create key in CURRENT USER and set it
            SetKeyValue(HKEY_CURRENT_USER, "Software\Unigraphics Solutions\Solid Edge\Version " & strSEVersion & "\Debug", "DocMgmt_OverrideStatusCheckForFileAccess", "1", REG_DWORD)
        End If

        If blnCheckAssemblyForCorruptLinks = True Then
            'need to set the registry switch to enable this....
            'check to see if registry location exists
            SwitchExists = QueryValue(HKEY_CURRENT_USER, "Software\Unigraphics Solutions\Solid Edge\Version " & strSEVersion & "\Debug", "WRITE_BADLINKS_TO_FILE")
            If SwitchExists = "" Then
                '-- Create key in CURRENT USER and set it
                SetKeyValue(HKEY_CURRENT_USER, "Software\Unigraphics Solutions\Solid Edge\Version " & strSEVersion & "\Debug", "WRITE_BADLINKS_TO_FILE", "1", REG_DWORD)
            End If
            If SwitchExists = "0" Then
                '-- Create key in CURRENT USER and set it
                SetKeyValue(HKEY_CURRENT_USER, "Software\Unigraphics Solutions\Solid Edge\Version " & strSEVersion & "\Debug", "WRITE_BADLINKS_TO_FILE", "1", REG_DWORD)
            End If
        End If



        '********************here is the big loop to process the files collected either from the dialog input( folder or textfile)
        Try
            For ii = 0 To StrFileNames.Count - 1

                Dim strExtension As String = ParseExtension(StrFileNames.Item(ii))
                If IsValdidFileToProcess(strExtension) = False Then
                    GoTo skip
                End If

                If blnRunFromCommandLine = False Then
                    If ii = 0 Then
                        OpenSaveForm.Controls.Item("Label2").Text = "processing 1 of " + StrFileNames.Count.ToString + " " + StrFileNames.Item(ii)
                        OpenSaveForm.Controls.Item("Label2").Refresh()
                    Else
                        OpenSaveForm.Controls.Item("Label2").Text = "processing " + ii.ToString + " of " + StrFileNames.Count.ToString + " " + StrFileNames.Item(ii)
                        OpenSaveForm.Controls.Item("Label2").Refresh()
                    End If
                End If

                If blnRunFromCommandLine = True Then
                    'Console.WriteLine("processing " + ii.ToString + " of " + StrFileNames.Count.ToString + " " + StrFileNames.Item(ii))
                End If

                If (GetAttr(StrFileNames(ii)) And FileAttribute.ReadOnly) <> 0 Then
                    txtStreamReportStatus.WriteLine("ERROR->ReadOnlyFile:" + StrFileNames.Item(ii))
                    GoTo skip
                End If

                If blnResetStatus = True Then
                    If ResetSEFileStatusToAvailable(StrFileNames.Item(ii)) = False Then
                        GoTo skip
                    End If     
                End If

                ' '' ''If UCase(StrFileNames(ii)).EndsWith("ASM") Then
                ' '' ''    ' To save time, rather than processing all assemblies, when
                ' '' ''    ' OpenSave is running, Assembly will save all subassemblies
                ' '' ''    ' when it saves a top-level assembly  0 is normal behavior 1 forces a save on subs
                ' '' ''    SetOpenSaveMacroFlag(0)
                ' '' ''End If


                If blnExtractPreviewBMP = True Then

                    Try
                        Dim junk As Object = Nothing

                        Dim oSEThumb As SeThumbnailLib.SeThumbnailExtractor
                        oSEThumb = CreateObject("SeThumbnail.SeThumbnailExtractor")
                        Dim hndlImage As Integer
                        oSEThumb.GetThumbnail(StrFileNames(ii), hndlImage, junk)
                        'got the handle now what to do with it!!!!!

                        Dim objBMP As System.Drawing.Bitmap = System.Drawing.Image.FromHbitmap(hndlImage)

                        Dim strtmpFname As String = StrFileNames(ii)
                        strtmpFname = System.IO.Path.ChangeExtension(strtmpFname, ".bmp")
                        objBMP.Save(filename:=strtmpFname)

                        Module1.Garbage_Collect(oSEThumb)
                        Module1.Garbage_Collect(objBMP)
                    Catch ex As Exception
                        MessageBox.Show("error getting bmp preview" + ex.Message)
                        End
                    End Try
                    GoTo skip
                End If




                Try
                    If ConnectToSolidEdge(intCtr) = True Then
                        ObjSEApp.DoIdle()
                        ObjSEApp.WindowState = 2  'maximize the app window

                        'open the current document in the loop
                        objDoc = ObjSEApp.Documents.Open(StrFileNames.Item(ii))

                        If objDoc.type = SolidEdgeFramework.DocumentTypeConstants.igDraftDocument Then
                            obj2dWindow = ObjSEApp.ActiveWindow
                            If blnFitAndShade = True Then
                                obj2dWindow.FitEx(SolidEdgeDraft.SheetFitConstants.igFitSheet)
                            End If
                            objDoc.UpdatePropertyTextDisplay()
                            If blnCreatePDFsFromDrafts = True Then
                                ' then create the PDF of draft files ONLY
                                strtempFilename = Mid(StrFileNames.Item(ii), 1, InStrRev(StrFileNames.Item(ii), ".", , CompareMethod.Text))
                                ObjSEApp.ActiveDocument.saveas(strtempFilename + "pdf")
                            End If
                            If blnUpdateDrawingViews = True Then
                                ObjSEApp.StartCommand(SolidEdgeConstants.DetailCommandConstants.DetailDrawingViewsUpdateViews)
                            End If
                        End If
                        vString = CStr(objDoc.lastsavedversion)
                        If objDoc.type = SolidEdgeConstants.DocumentTypeConstants.igPartDocument Then
                            obj3dWindow = ObjSEApp.ActiveWindow
                            obj3dWindow.WindowState = 2

                            If blnRecompute = True Then
                                objDoc.recompute()
                            End If

                            If blnFitAndShade = True Then
                                ObjSEApp.StartCommand(SolidEdgeConstants.PartCommandConstants.PartViewISOView)
                                ObjSEApp.StartCommand(SolidEdgeConstants.PartCommandConstants.PartReferencePlaneHideAllReferencePlanes)
                                obj3dWindow.View.RenderModeType = SolidEdgeFramework.SeRenderModeType.seRenderModeSmoothVHL
                                ObjSEApp.StartCommand(SolidEdgeConstants.PartCommandConstants.PartViewFit)
                            End If
                        End If



                        If objDoc.type = SolidEdgeConstants.DocumentTypeConstants.igSheetMetalDocument Then
                            obj3dWindow = ObjSEApp.ActiveWindow
                            obj3dWindow.WindowState = 2

                            If blnRecompute = True Then
                                objDoc.recompute()
                                objFlatPatternModels = objDoc.flatpatternmodels
                                If objFlatPatternModels.Count > 0 Then
                                    For pp = 1 To objFlatPatternModels.Count
                                        objFlatPatternModel = objFlatPatternModels.Item(pp)
                                        objFlatPatternModel.Recompute()
                                        objFlatPatternModel.Update()
                                    Next pp
                                End If
                            End If

                            If blnFitAndShade = True Then
                                ObjSEApp.StartCommand(SolidEdgeConstants.SheetMetalCommandConstants.SheetMetalViewISOView)
                                ObjSEApp.StartCommand(SolidEdgeConstants.SheetMetalCommandConstants.SheetMetalReferencePlaneHideAllReferencePlanes)
                                obj3dWindow.View.RenderModeType = SolidEdgeFramework.SeRenderModeType.seRenderModeSmoothVHL
                                ObjSEApp.StartCommand(SolidEdgeConstants.SheetMetalCommandConstants.SheetMetalViewFit)
                            End If
                        End If

                        If objDoc.type = SolidEdgeConstants.DocumentTypeConstants.igAssemblyDocument Then
                            obj3dWindow = ObjSEApp.ActiveWindow
                            obj3dWindow.WindowState = 2

                            Dim junk As Integer = objDoc.variables.count


                            If blnFitAndShade = True Then
                                ObjSEApp.StartCommand(SolidEdgeConstants.AssemblyCommandConstants.AssemblyViewISOView)
                                ObjSEApp.StartCommand(SolidEdgeConstants.AssemblyCommandConstants.AssemblyAssemblyToolsHideAllReferencePlanes)
                                obj3dWindow.View.RenderModeType = SolidEdgeFramework.SeRenderModeType.seRenderModeSmoothVHL
                                ObjSEApp.StartCommand(SolidEdgeConstants.AssemblyCommandConstants.AssemblyViewFit)
                            End If

                            If blnCheckAssemblyForCorruptLinks = True Then
                                blnCorruptLinkFileProcessed = False
                                Try
                                    Dim strTempFolder As String = System.IO.Path.GetTempPath
                                    If System.IO.File.Exists(strTempFolder + "InvalidLinks.txt") = True Then
                                        System.IO.File.Delete(strTempFolder + "InvalidLinks.txt")
                                    End If
                                    ObjSEApp.StartCommand(64000)
                                    ObjSEApp.DoIdle()   'during my testing seemed to be a timing thing... sometime did not report an issue  this API or the sleep below seemed to make it work... need to check into this

                                    If System.IO.File.Exists(strTempFolder + "InvalidLinks.txt") = True Then
                                        blnCorruptLinkFileProcessed = True
                                        Dim strInvalidLinks As String = ""
                                        strInvalidLinks = ReadInvalidLinksFile(strTempFolder + "InvalidLinks.txt")
                                        txtStreamReportStatus.WriteLine("CORRUPT LINKS FOUND IN FILE : " + StrFileNames.Item(ii) + " invalid links are->" + strInvalidLinks)
                                    End If
                                    System.IO.File.Delete(strTempFolder + "InvalidLinks.txt")  'remove it
                                Catch ex As Exception
                                    Dim strTempFolder As String = System.IO.Path.GetTempPath
                                    txtStreamReportStatus.WriteLine("Error could not delete the file : " + strTempFolder + "InvalidLinks.txt")
                                    GoTo skip
                                End Try
                            End If
                        End If

                        If objDoc.type = SolidEdgeConstants.DocumentTypeConstants.igWeldmentDocument Then
                            obj3dWindow = ObjSEApp.ActiveWindow
                            obj3dWindow.WindowState = 2
                            If blnFitAndShade = True Then
                                ObjSEApp.StartCommand(SolidEdgeConstants.WeldmentCommandConstants.WeldmentViewISOView)
                                ObjSEApp.StartCommand(SolidEdgeConstants.WeldmentCommandConstants.WeldmentReferencePlaneHideAllReferencePlanes)
                                obj3dWindow.View.RenderModeType = SolidEdgeFramework.SeRenderModeType.seRenderModeSmoothVHL
                                ObjSEApp.StartCommand(SolidEdgeConstants.WeldmentCommandConstants.WeldmentViewFit)
                            End If

                        End If

                        If objDoc.type = SolidEdgeConstants.DocumentTypeConstants.igWeldmentAssemblyDocument Then
                            obj3dWindow = ObjSEApp.ActiveWindow
                            obj3dWindow.WindowState = 2
                            If blnFitAndShade = True Then
                                ObjSEApp.StartCommand(SolidEdgeConstants.AssemblyCommandConstants.AssemblyViewISOView)
                                ObjSEApp.StartCommand(SolidEdgeConstants.AssemblyCommandConstants.AssemblyAssemblyToolsHideAllReferencePlanes)
                                obj3dWindow.View.RenderModeType = SolidEdgeFramework.SeRenderModeType.seRenderModeSmoothVHL
                                ObjSEApp.StartCommand(SolidEdgeConstants.AssemblyCommandConstants.AssemblyViewFit)
                            End If

                        End If


                        objDoc.Save()
                        'txtStreamReportStatus.WriteLine("Successfully saved : File: " + StrFileNames.Item(ii))
                        objDoc.Close(False)


                        If blnCheckAssemblyForCorruptLinks = True And blnCorruptLinkFileProcessed = False Then  'due to poissible timing issues check one more time
                            Dim strTempFolder As String = System.IO.Path.GetTempPath
                            If System.IO.File.Exists(strTempFolder + "InvalidLinks.txt") = True Then
                                blnCorruptLinkFileProcessed = True
                                Dim strInvalidLinks As String = ""
                                strInvalidLinks = ReadInvalidLinksFile(strTempFolder + "InvalidLinks.txt")
                                txtStreamReportStatus.WriteLine("CORRUPT LINKS FOUND IN FILE : " + StrFileNames.Item(ii) + " invalid links are->" + strInvalidLinks)
                            End If
                            System.IO.File.Delete(strTempFolder + "InvalidLinks.txt")  'remove it
                        End If


                    End If

                Catch ex As Exception
                    txtStreamReportStatus.WriteLine("Error saving File:" + StrFileNames.Item(ii) + " " + ex.Message)
                    objDoc.Close(False)
                    intCtr = intMaxNumberThenRestart - 1
                    GoTo skip
                End Try

skip:
                intCtr = intCtr + 1
                strtempFilename = ""

                Garbage_Collect(obj2dWindow)
                Garbage_Collect(obj3dWindow)
                Garbage_Collect(objModel)
                Garbage_Collect(objModels)
                Garbage_Collect(objFlatPatternModel)
                Garbage_Collect(objFlatPatternModels)
                Garbage_Collect(objDoc)

            Next


        Catch ex As Exception
            txtStreamReportStatus.WriteLine("Catastrophic failure exiting for this set of files:" + StrFileNames.Item(ii) + " " + ex.Message)
        End Try


        txtStreamReportStatus.WriteLine("Finished processing files " + Date.Now.ToString)


        txtStreamReportStatus.Close()
        Garbage_Collect(txtStreamReportStatus)
        Garbage_Collect(FSOLog)


        Try
            ObjSEApp.Quit()
            Garbage_Collect(ObjSEApp)
        Catch ex As Exception

        End Try

        If blnRunFromCommandLine = False Then
            OpenSaveForm.Controls.Item("Button4").Enabled = True
        End If

        '-- Reset back to 0 to get normal behavior
        SetKeyValue(HKEY_CURRENT_USER, "Software\Unigraphics Solutions\Solid Edge\Version " & strSEVersion & "\Debug", "DocMgmt_OverrideStatusCheckForFileAccess", "0", REG_DWORD)

        If blnCheckAssemblyForCorruptLinks = True Then
            SetKeyValue(HKEY_CURRENT_USER, "Software\Unigraphics Solutions\Solid Edge\Version " & strSEVersion & "\Debug", "WRITE_BADLINKS_TO_FILE", "0", REG_DWORD)
        End If










        OpenSaveForm.Controls.Item("Label2").Text = "Finished processing."
        OpenSaveForm.Controls.Item("Label2").Refresh()

        '******* Added because of .NET
        Try
            OleMessageFilter.Revoke()
        Catch ex As Exception
            PrintLine("Error revoking the message filter.")
        End Try
        '******* Added because of .NET

        If blnRunFromCommandLine = True Then
            End
        End If


    End Sub

    Public Function ParseExtension(ByVal fname As String) As String

        Dim nstart As Long


        nstart = InStrRev(fname, ".", -1, Microsoft.VisualBasic.CompareMethod.Text)

        If nstart <> 0 Then
            ParseExtension = Mid(fname, nstart + 1, Len(fname))
            Exit Function
        End If

        If nstart = 0 Then
            ParseExtension = ""
            Exit Function
        End If

        ParseExtension = ""


    End Function

    Public Function IsValdidFileToProcess(ByVal oFileExtension As String) As Boolean

        IsValdidFileToProcess = False

        If InStr(UCase(oFileExtension), "ASM", CompareMethod.Text) <> 0 Then
            IsValdidFileToProcess = True
            Exit Function
        End If

        If InStr(UCase(oFileExtension), "PAR", CompareMethod.Text) <> 0 Then
            IsValdidFileToProcess = True
            Exit Function
        End If


        If InStr(UCase(oFileExtension), "PSM", CompareMethod.Text) <> 0 Then
            IsValdidFileToProcess = True
            Exit Function
        End If

        If InStr(UCase(oFileExtension), "PWD", CompareMethod.Text) <> 0 Then
            IsValdidFileToProcess = True
            Exit Function
        End If

        If InStr(UCase(oFileExtension), "DFT", CompareMethod.Text) <> 0 Then
            IsValdidFileToProcess = True
            Exit Function
        End If

    End Function

    Public Function ConnectToSolidEdge(ByVal oCount As Integer) As Boolean
        Dim blnRestart As Boolean

        blnRestart = False

        If oCount >= intMaxNumberThenRestart Then
            If blnRunFromCommandLine = False Then
                OpenSaveForm.Controls.Item("Label2").Text = "Closing and restarting Solid Edge"
                OpenSaveForm.Controls.Item("Label2").Refresh()
            End If
            blnRestart = True
            Try
                intCtr = 0
                Do While ObjSEApp.Documents.Count <> 0
                    ObjSEApp.DisplayAlerts = False
                    ObjSEApp.ActiveDocument.close()
                Loop
                ObjSEApp.Quit()
                Garbage_Collect(ObjSEApp)

            Catch ex As Exception
                KillProcess("Edge.exe")
                Garbage_Collect(ObjSEApp)
            End Try

        End If



        'to connect to a running instance of Solid Edge
        Try
StartOver:
            ObjSEApp = Marshal.GetActiveObject("SolidEdge.Application")
            ObjSEApp.DisplayAlerts = False
            ObjSEApp.Visible = True
            ConnectToSolidEdge = True
            ObjSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, False)

            If blnRestart = True Then
                If blnRunFromCommandLine = False Then
                    OpenSaveForm.Controls.Item("Label2").Text = ""
                    OpenSaveForm.Controls.Item("Label2").Refresh()
                End If

            End If
            ConnectToSolidEdge = True
            Exit Function

        Catch ex As System.Exception

            'SE not running then start it
            Try
                ObjSEApp = Activator.CreateInstance(ObjSEAppType)
                ObjSEApp.DisplayAlerts = False
                ObjSEApp.Visible = True
                ConnectToSolidEdge = True
                ObjSEApp.SetGlobalParameter(SolidEdgeFramework.ApplicationGlobalConstants.seApplicationGlobalTeamCenterMode, False)
            Catch ex2 As Exception
                MsgBox("Could not Start Solid Edge", MsgBoxStyle.OkOnly)
            End Try

            If blnRestart = True Then
                If blnRunFromCommandLine = False Then
                    OpenSaveForm.Controls.Item("Label2").Text = ""
                    OpenSaveForm.Controls.Item("Label2").Refresh()
                End If

            End If
            ConnectToSolidEdge = True
            Exit Function
        End Try

        If ObjSEApp Is Nothing Then
            MsgBox("Could not Start Solid Edge", MsgBoxStyle.OkOnly)
        End If

        ConnectToSolidEdge = False



    End Function

    Public Function KillProcess(ByVal Name As String) As Long

        Dim LocalProcs As Process()
        Dim Proc As Process
        Dim i As Integer
        Dim blnProcessTerminated As Boolean
        blnProcessTerminated = False

        LocalProcs = System.Diagnostics.Process.GetProcesses
        For Each Proc In LocalProcs
            If UCase(Proc.ProcessName) = UCase(Name) Then
                Try
                    Proc.Kill()
                    KillProcess = 0
                    blnProcessTerminated = True
                Catch ex As System.Exception
                    KillProcess = 1
                    LocalProcs = Nothing
                    Exit Function
                End Try
            End If
            i += 1
        Next

        If blnProcessTerminated = True Then
            KillProcess = 0
        End If

        If blnProcessTerminated = False Then
            KillProcess = -2
        End If

    End Function

    

    Public Sub ReadTextFile()
        Dim FSOTextFile As Scripting.FileSystemObject = Nothing
        Dim oStream As Scripting.TextStream = Nothing
        'Dim strtmpTCNumber As String
        'Dim strtmpTCREvision As String
        Dim strTmp As String
        Dim pstart As Integer

        Try
            FSOTextFile = New Scripting.FileSystemObject
            oStream = FSOTextFile.OpenTextFile(strInputFilename, Scripting.IOMode.ForReading, False, Scripting.Tristate.TristateUseDefault)
            Do While Not oStream.AtEndOfStream
                strTmp = oStream.ReadLine
                StrFileNames.Add(strTmp)
                pstart = 0

skip:
                strTmp = ""
            Loop

            oStream.Close()

        Catch ex As Exception

        End Try


        Garbage_Collect(oStream)
        Garbage_Collect(FSOTextFile)


    End Sub

    Public Function createLogFile() As Boolean

        Try
            If FSOLog Is Nothing Then
                FSOLog = New Scripting.FileSystemObject
            End If

            If FSOLog.FileExists(strLogFilename) = True Then
                FSOLog.DeleteFile(strLogFilename)
            End If

            txtStreamReportStatus = FSOLog.OpenTextFile(strLogFilename, Scripting.IOMode.ForAppending, True, Scripting.Tristate.TristateUseDefault)
            txtStreamReportStatus.WriteLine("Begin processing files  " + Date.Now.ToString)
            createLogFile = True

            Exit Function
        Catch ex As Exception
            MsgBox("Error creating text file to containing import status " + strLogFilename, MsgBoxStyle.Critical)
            End
        End Try

        createLogFile = False

    End Function

    Public Function GetFilePath(ByVal strFname As String) As String
        Dim intStringLength As Integer
        Dim rstart As Integer
        Dim temp As String
        Dim strPathWithNoFileName As String

        intStringLength = Len(strFname)
        rstart = InStrRev(strFname, "\")
        If rstart = 0 Then
            GetFilePath = ""
            Exit Function
        End If
        temp = Mid(strFname, intStringLength - 3, 1)
        strPathWithNoFileName = Mid(strFname, 1, rstart - 1)
        GetFilePath = Mid(strFname, 1, rstart - 1)


    End Function



    Public Function ParseCommandlineInput(ByVal strCmdLine As String) As String


        Dim nstart As Integer

        Dim kk As Integer = 0

        If InStr(strCmdLine, "-i=") <> 0 Then  'means we have the input filename string
            nstart = InStr(strCmdLine, "-i=")
            ParseCommandlineInput = Mid(strCmdLine, nstart + 3, Len(strCmdLine))
            strCommandLineInputFilename = Mid(strCmdLine, nstart + 3, Len(strCmdLine))
            nstart = 0
            Exit Function

        ElseIf InStr(strCmdLine, "-pdf=") <> 0 Then  ' should be -pdf=TRUE or -pdf=FALSE whether or not to create PDF from draft files
            nstart = InStr(strCmdLine, "-pdf=")
            ParseCommandlineInput = Mid(strCmdLine, nstart + 5, Len(strCmdLine))
            strCommandLineCreatePDFs = Mid(strCmdLine, nstart + 5, Len(strCmdLine))
            nstart = 0
            Exit Function

        ElseIf InStr(strCmdLine, "-checkAssembly=") <> 0 Then  'should be -run=TRUE or -run=FALSE whether or not to run the check for invalid links on only assemblies
            nstart = InStr(strCmdLine, "-checkAssembly=")
            ParseCommandlineInput = Mid(strCmdLine, nstart + 15, Len(strCmdLine))
            strCommandLineInputCheckAssembliesForCorruptLinks = Mid(strCmdLine, nstart + 15, Len(strCmdLine))
            nstart = 0
            Exit Function

        ElseIf InStr(strCmdLine, "-fit=") <> 0 Then  'should be -fit=TRUE or -fit=FALSE whether or not to fit and shade models before saving
            nstart = InStr(strCmdLine, "-fit=")
            ParseCommandlineInput = Mid(strCmdLine, nstart + 5, Len(strCmdLine))
            strCommandLineInputFitAndShade = Mid(strCmdLine, nstart + 5, Len(strCmdLine))
            nstart = 0
            Exit Function


        ElseIf InStr(strCmdLine, "-recompute=") <> 0 Then  'should be -fit=TRUE or -fit=FALSE whether or not to fit and shade models before saving
            nstart = InStr(strCmdLine, "-recompute=")
            ParseCommandlineInput = Mid(strCmdLine, nstart + 11, Len(strCmdLine))
            strCommandLineInputRecompute = Mid(strCmdLine, nstart + 11, Len(strCmdLine))
            nstart = 0
            Exit Function

        ElseIf InStr(strCmdLine, "-updateDraft=") <> 0 Then  'should be -fit=TRUE or -fit=FALSE whether or not to update drawing views before saving
            nstart = InStr(strCmdLine, "-updateDraft=")
            ParseCommandlineInput = Mid(strCmdLine, nstart + 13, Len(strCmdLine))
            strCommandLineInputUpdateDrawingViews = Mid(strCmdLine, nstart + 11, Len(strCmdLine))
            nstart = 0
            Exit Function

        ElseIf InStr(strCmdLine, "-resetStatus=") <> 0 Then  'should be -fit=TRUE or -fit=FALSE whether or not to update drawing views before saving
            nstart = InStr(strCmdLine, "-resetStatus=")
            ParseCommandlineInput = Mid(strCmdLine, nstart + 13, Len(strCmdLine))
            strCommandLineInputResetStatus = Mid(strCmdLine, nstart + 11, Len(strCmdLine))
            nstart = 0
            Exit Function

        Else


            ParseCommandlineInput = ""
        End If




    End Function





    Public Sub ReadFilenamesFromCSVFile(ByVal strCSVFilename As String)

        Dim oCSV As Scripting.TextStream = Nothing
        Dim strtmpLine As String = ""
        Dim strTmpFilename As String = ""
        Dim items() As String
        Dim strOrderNumber As String
        Dim strFileNameWithPath As String
        Dim strFileNameOnly As String
        Dim strPathOnly As String
        Dim strTemp As String
        Dim str1 As String = ""
        Dim str2 As String = ""
        Dim str3 As String = ""
        Dim strTemp1 As String = ""
        Dim strTemp2 As String = ""
        Dim strTemp3 As String = ""
        Dim strTemp4 As String = ""
        Dim strTemp5 As String = ""
        Dim strtmpTextFilename As String = ""

        Dim blnParseMethod1 As Boolean = False



        Dim nstart As Integer
        Dim pstart As Integer

        If (FSO Is Nothing) Then
            FSO = New Scripting.FileSystemObject
        End If


        strtmpTextFilename = FSO.GetBaseName(strCSVFilename)

        If FSO.FileExists(GetFilePath(strCSVFilename) + "\" + strtmpTextFilename + ".txt") = True Then
            FSO.DeleteFile(GetFilePath(strCSVFilename) + "\" + strtmpTextFilename + ".txt", True)
        End If


        Dim oTxt As Scripting.TextStream = Nothing

        Try
            oCSV = FSO.OpenTextFile(strCSVFilename, Scripting.IOMode.ForReading, False)
            oTxt = FSO.OpenTextFile(GetFilePath(strCSVFilename) + "\" + strtmpTextFilename + ".txt", Scripting.IOMode.ForAppending, True, Scripting.Tristate.TristateUseDefault)
        Catch ex As Exception
            'Beep()
        End Try

        Try

            Do While Not oCSV.AtEndOfStream
                strtmpLine = oCSV.ReadLine
                ' commented out v 29  strtmpLine = Mid(strtmpLine, 2, Len(strtmpLine) - 2)
                items = Split(strtmpLine, Chr(34) + "," + Chr(34))

                If oCSV.Line = 1 Then
                    GoTo skip
                End If
                If oCSV.Line = 2 Then
                    GoTo skip
                End If

                If oCSV.Line = 3 Then
                    GoTo skip
                End If

                If InStr(strtmpLine, "Unordered") <> 0 Then
                    GoTo skip
                End If

                If InStr(strtmpLine, "Ordered") <> 0 Then
                    GoTo skip
                End If

                If InStr(strtmpLine, "Reverse Link") <> 0 Then
                    GoTo skip
                End If

                If InStr(strtmpLine, "Order Number") <> 0 Then
                    GoTo skip
                End If

                If oCSV.Line >= 4 Then
                    '*******   in V29 to fix problem reading the csv file for all locales
                    nstart = InStr(strtmpLine, Chr(34), CompareMethod.Text)

                    If nstart <> 0 Then
                        strTemp1 = Mid(strtmpLine, nstart + 1, Len(strtmpLine))
                        pstart = InStr(strTemp1, Chr(34), CompareMethod.Text)
                        str1 = Mid(strTemp1, 1, pstart - 1)
                        strTemp2 = Mid(strTemp1, pstart + 1, Len(strTemp1))
                        nstart = InStr(strTemp2, Chr(34), CompareMethod.Text)
                        If nstart <> 0 Then
                            strTemp3 = Mid(strTemp2, nstart + 1, Len(strTemp2))
                            pstart = InStr(strTemp3, Chr(34), CompareMethod.Text)
                            str2 = Mid(strTemp3, 1, pstart - 1)
                            strTemp4 = Mid(strTemp3, pstart + 1, Len(strTemp3))
                            nstart = InStr(strTemp4, Chr(34), CompareMethod.Text)
                            If nstart <> 0 Then
                                strTemp5 = Mid(strTemp4, nstart + 1, Len(strTemp2))
                                pstart = InStr(strTemp5, Chr(34), CompareMethod.Text)
                                str3 = Mid(strTemp5, 1, pstart - 1)
                            End If
                        End If
                    End If

                    If str3 <> "" Then   ' means it is a reverse link file so do not add a second time to files to be processed
                        GoTo skip
                    End If

                    strOrderNumber = str1
                    strFileNameWithPath = str2

                    If StrFileNames.Count = 0 Then
                        StrFileNames.Add(strFileNameWithPath)
                        oTxt.WriteLine(strFileNameWithPath)
                        DummySpreadsheetList.Add(UCase(strFileNameWithPath))

                    Else
                        If DummySpreadsheetList.Contains(UCase(strFileNameWithPath)) = False Then
                            StrFileNames.Add(strFileNameWithPath)
                            oTxt.WriteLine(strFileNameWithPath)
                            DummySpreadsheetList.Add(UCase(strFileNameWithPath))

                        End If
                    End If





                End If
skip:
                strtmpLine = ""
                strOrderNumber = ""
                strFileNameWithPath = ""
                strFileNameOnly = ""
                strPathOnly = ""
                strTemp = ""
                nstart = 0
                pstart = 0
                strTmpFilename = ""
                str1 = ""
                str2 = ""
                str3 = ""
                strTemp1 = ""
                strTemp2 = ""
                strTemp3 = ""
                strTemp4 = ""
                strTemp5 = ""


            Loop
            oCSV.Close()
            oTxt.Close()
        Catch ex As Exception
            'Beep()
        End Try
        Garbage_Collect(oTxt)
        Garbage_Collect(oCSV)

    End Sub


    Public Sub ShellandWait(ByVal ProcessPath As String, ByVal arguments As String)

        Try
            Dim myProcess As Process = System.Diagnostics.Process.Start(ProcessPath, arguments)
            myProcess.WaitForExit()
            myProcess.Close()
            myProcess.Dispose()

        Catch ex As Exception
            'possibly need to raise an error
        End Try
       

    End Sub

    Public Function ResetSEFileStatusToAvailable(ByVal oFilename As String) As Boolean
        Dim Objproperties As SolidEdgeFileProperties.Properties
        Dim objproperty As SolidEdgeFileProperties.Property
        Dim PropertySets As SolidEdgeFileProperties.PropertySets

        Try
            PropertySets = New SolidEdgeFileProperties.PropertySets
            PropertySets.Open(oFilename)
            Objproperties = PropertySets.Item("ExtendedSummaryInformation")
            objproperty = Objproperties.PropertyByID(SolidEdgeFileProperties.PropertyIDs.igExtSumInfoStatus)
            If objproperty.Value <> SolidEdgeConstants.DocumentStatus.igStatusAvailable Then
                If objproperty.Value = SolidEdgeConstants.DocumentStatus.igStatusReleased Then
                    PropertySets.Item("Custom").add("TC_SEStatus", "Released")
                ElseIf objproperty.Value = SolidEdgeConstants.DocumentStatus.igStatusObsolete Then
                    PropertySets.Item("Custom").add("TC_SEStatus", "Obselete")
                ElseIf objproperty.Value = SolidEdgeConstants.DocumentStatus.igStatusInWork Then
                    PropertySets.Item("Custom").add("TC_SEStatus", "InWork")
                ElseIf objproperty.Value = SolidEdgeConstants.DocumentStatus.igStatusInReview Then
                    PropertySets.Item("Custom").add("TC_SEStatus", "InReview")
                ElseIf objproperty.Value = SolidEdgeConstants.DocumentStatus.igStatusBaselined Then
                    PropertySets.Item("Custom").add("TC_SEStatus", "Baselined")
                End If
                objproperty.Value = SolidEdgeConstants.DocumentStatus.igStatusAvailable
                Objproperties = PropertySets.Item("SummaryInformation")
                objproperty = Objproperties.PropertyByID(SolidEdgeFileProperties.PropertyIDs.igSumInfoDocSecurity)
                objproperty.Value = SolidEdgeConstants.DocumentStatus.igStatusAvailable
                PropertySets.Save()
                PropertySets.Close()
                Garbage_Collect(objproperty)
                Garbage_Collect(Objproperties)
                Garbage_Collect(PropertySets)
                Exit Try
            End If
            PropertySets.Close()
            Garbage_Collect(objproperty)
            Garbage_Collect(Objproperties)
            Garbage_Collect(PropertySets)
            ResetSEFileStatusToAvailable = True
            Exit Function
        Catch ex As Exception
            txtStreamReportStatus.WriteLine("ERROR->Status can not be set to available:" + oFilename + " " + ex.Message)
        End Try



        ResetSEFileStatusToAvailable = False
    End Function

    Public Function ReadInvalidLinksFile(ByVal oFile As String) As String

        Dim FSO As Scripting.FileSystemObject = Nothing
        Dim oText As Scripting.TextStream = Nothing
        Dim strReadLine As String = ""
        Dim strBadLinks As String = ""
        Try
            FSO = New Scripting.FileSystemObject
            oText = FSO.OpenTextFile(oFile, Scripting.IOMode.ForReading, False, Scripting.Tristate.TristateUseDefault)
            Do While Not oText.AtEndOfStream
                strReadLine = oText.ReadLine
                If InStr(strReadLine, Chr(9), CompareMethod.Text) <> 0 Then
                    strBadLinks = strBadLinks + " " + Mid(strReadLine, InStr(strReadLine, Chr(9), CompareMethod.Text) + 1, Len(strReadLine))
                End If
            Loop
            oText.Close()
            ReadInvalidLinksFile = strBadLinks
            Garbage_Collect(oText)
            Garbage_Collect(FSO)
            Exit Function
        Catch ex As Exception
            Beep()

        End Try


        ReadInvalidLinksFile = ""
    End Function
End Module
